package me.numark.activities;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import butterknife.Bind;
import me.numark.R;
import me.numark.fragments.BaseListFragment;
import me.numark.fragments.CommentsFragment;
import me.numark.model.Topic;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;

/**
 * Created by Evan on 15/7/25.
 */
public class CommentBaseActivity extends BaseActivity implements
        MarkDetailActivity.OnCommentsFragmentInteractionListener, AppBarLayout.OnOffsetChangedListener, GestureDetector.OnGestureListener, View.OnClickListener {

    @Bind(R.id.viewpager)
    @Nullable
    public ViewPager pager;

    @Bind(R.id.radio_left)
    @Nullable
    RadioButton leftRadio;

    @Bind(R.id.radio_right)
    @Nullable
    RadioButton rightRadio;

    @Bind(R.id.radio_center)
    @Nullable
    RadioButton centerRadio;

    @Bind(R.id.radio_group)
    @Nullable
    RadioGroup radioGroup;

    @Bind(R.id.inputbar)
    @Nullable
    FrameLayout inputbar;

    @Bind(R.id.input_edit)
    @Nullable
    EditText inputEdit;

    @Bind(R.id.input_btn)
    @Nullable
    Button inputButton;

    @Bind(R.id.appBarLayout)
    @Nullable
    AppBarLayout appBarLayout;

    @Bind(R.id.coordinator)
    @Nullable
    CoordinatorLayout mCoordinatorLayout;

    Topic currentReplyTopic;
    BaseListFragment[] fragments;
    GestureDetectorCompat mDetector;
    int maxScrollOffset;
    Dialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
        mDetector = new GestureDetectorCompat(this, this);
        maxScrollOffset = appBarLayout.getTotalScrollRange();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (appBarLayout != null)
            appBarLayout.addOnOffsetChangedListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (appBarLayout != null)
            appBarLayout.removeOnOffsetChangedListener(this);
    }

    @Override
    public void onClickComment(Topic topic) {
        if (inputEdit.getText().length() > 0) {
            return;
        }
        currentReplyTopic = topic;
        if (topic == null) {
            inputEdit.setHint(R.string.comment_hint);
        } else {
            if (topic.user.uid == Global.getCurrentUid()){
                showDialog();
            }else {
                inputEdit.setHint(getString(R.string.comment_reply_hint, topic.user.nick));
            }
        }
    }

    void showDialog() {
        View view = getLayoutInflater().inflate(R.layout.delete_topic, null);
        Button deleteBtn = (Button) view.findViewById(R.id.btn_delete);
        Button cancelBtn = (Button)view.findViewById(R.id.btn_cancel);

        deleteBtn.setOnClickListener(this);

        cancelBtn.setOnClickListener(this);
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();

        window.setWindowAnimations(R.style.menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();

        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int offset) {
        for (BaseListFragment fragment : fragments) {
            if (fragment != null)
                fragment.enableRefresh(offset == 0);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mDetector.onTouchEvent(event) || super.onTouchEvent(event);
    }



    @Override
    public boolean onDown(MotionEvent e) {
        int[] l = new int[2];
        appBarLayout.getLocationOnScreen(l);
        int x = l[0];
        int y = l[1];
        int w = appBarLayout.getWidth();
        int h = appBarLayout.getHeight();
        int rx = (int) e.getRawX();
        int ry = (int) e.getRawY();
        if (rx < x || rx > x + w || ry < y || ry > y + h) {
            return false;
        }
        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        scrollAppBar((int) distanceY);
        return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    void scrollAppBar(int y) {
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
        AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
        int offset = behavior.getTopAndBottomOffset() - y;
        if (offset > 0)
            offset = 0;
        if (maxScrollOffset == 0)
            maxScrollOffset = appBarLayout.getTotalScrollRange();
        if (offset < -maxScrollOffset)
            offset = -maxScrollOffset;
        behavior.setTopAndBottomOffset(offset);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_cancel:
                dialog.dismiss();
                break;
            case R.id.btn_delete:
                dialog.dismiss();
                new RequestServerTask<BaseResponse>(BaseResponse.class, this, this.getString(R.string.deleting)) {
                    @Override
                    protected String requestServer() {
                        String url = String.format(NetworkConstants.TOPIC_DELETE_URL, Global.getCurrentUid(), currentReplyTopic.tid);
                        return HttpUtil.get(url, null);
                    }

                    @Override
                    protected void onSuccess(BaseResponse result) {
                        Intent intent = new Intent(Constants.ACTION_TOPIC_DELETED);
                        intent.putExtra(Constants.COMMENT_TID_EXTRA, currentReplyTopic.tid);
                        LocalBroadcastManager.getInstance(CommentBaseActivity.this).sendBroadcast(intent);
                    }
                }.start();
                break;
        }
    }
}
